﻿using System;
using System.Web.UI.WebControls;
using eCommerce.core;
using eCommerce.core.Helpers;
using eCommerce.db;
using eCommerce.db.BORespository;
using eCommerce.db.Cart;

namespace eCommerce.web.Ajax.Common
{
    public partial class Cart : System.Web.UI.Page
    {
        protected string IsShow = "none";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                ListCart();
        }

        protected void ListCart()
        {            
            ltTotalCart.Text = Utils.FormatPrice(ShoppingCart.Instance.GetSubTotal());
            if (ShoppingCart.Instance.GetSubTotal() == 0)
                ltCart.Text = "-";
            else
            {
                IsShow = "block";
                ltCart.Text = string.Format("{0} <span style=\"font-size: 11px\">(VND)</span>", Utils.FormatPrice(ShoppingCart.Instance.GetSubTotal()));
                rptCart.DataSource = ShoppingCart.Instance.Items;
                rptCart.DataBind();                
            }
        }

        protected void rptCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var ltName      = (Literal)e.Item.FindControl("ltName");
                var ltImage     = (Literal)e.Item.FindControl("ltImage");
                var ltTotalItem = (Literal)e.Item.FindControl("ltTotalItem");

                var productId = Utils.ToInt32(((HiddenField)e.Item.FindControl("hfProduct")).Value);
                var quantity  = Utils.ToInt32(((HiddenField)e.Item.FindControl("hfQuantity")).Value);

                var o = ProductBo.GetById(productId);
                if (o != null)
                {
                    ltImage.Text = string.Format(Constant.ThumbImage, productId, (int)SettingType.Product, Utils.GetSetting("ThumbSize60", SettingType.Int32));
                    ltName.Text  = string.Format("<a href=\"{0}\">{1}</a>",
                                        UrlHelper.ProductDetail(CategoryBo.GetCategoryName(o.CategoryId), o.ProductId, o.Name), o.Code); //o.Code + "-" + o.Name

                    if (productId > 0 && quantity > 0)
                        ltTotalItem.Text = Utils.FormatPrice(Utils.ToDecimal(o.UnitPrice * quantity));
                }
            }
        }
    }
}